package com.huanying.sales.building;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huanying.framework.BaseDao;
import com.huanying.sales.region.Region;

@Service
public class BuildingServiceImpl implements BuildingService {
	
	Logger logger = Logger.getLogger(BuildingServiceImpl.class);
	
	@Autowired
	private BaseDao dao;

	@Override
	public void add(Building building) throws Exception {
		Session session = dao.getNewSession();
		Transaction tx = session.beginTransaction();
		try {
			session.save(building);
			Region r = (Region)dao.load(Region.class, building.getRegion_id());
			r.setTotal_num(r.getTotal_num()+1);
			session.update(r);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			logger.error("新建楼宇失败", e);
			throw e;
		}
		finally {
			session.flush();
			session.clear();
			session.close();
		}
	}

	@Override
	public void update(Building building) throws Exception {
		dao.update(building);
	}

	@Override
	public void delete(Building building) throws Exception {
		dao.delete(building);
	}

	@Override
	public Building get(int id) throws Exception {
		return (Building)dao.load(Building.class, id);
	}

	@Override
	public List getByRegionId(int id) throws Exception {
		String hql="from Building where region_id=:region_id and status=1";
		Building b = new Building();
		b.setRegion_id(id);
		List l = dao.exculeHql(hql, b);
		return l;
	}

}
